﻿using System;
using System.IO;
using System.Linq;
using Logging;
using Roslyn.Services;
using System.Collections.Generic;

namespace QueryGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            string logFile = @"s:\log\"
                + new FileInfo(args[0]).Name
                + "querygen"
                + "." + DateTime.Now.ToString("s").Replace(":", "")
                + ".txt";
            Logger.SetOutputFile(File.Open(logFile, FileMode.Create));

            Logger.PrintLine("Filename: " + args[0]);
            new Program(args[0]).GenerateQueries();
            Logger.PrintHeader("DONE");
            Logger.Close();
        }

        private IWorkspace currentWorkspace;
        private ISolution currentSolution;
        private IProject currentProject;
        protected IDocument CurrentDocument { get; private set; }

        public Program(string solution)
        {
            LoadSolution(solution);
        }

        void LoadSolution(string solutionPath)
        {
            // Workaround for known bug:
            // http://connect.microsoft.com/VisualStudio/feedback/details/698292/workspace-loadsolution-loads-projects-references-for-mscorlib-and-system-core-only
            currentWorkspace = Workspace.LoadSolution(solutionPath);
            if (currentWorkspace.CurrentSolution.Projects
                .All(p =>
                    {
                        try { return p.MetadataReferences.Count() <= 2; }
                        catch (Exception) { return true; }
                    }))
            {
                currentWorkspace = Workspace.LoadSolution(solutionPath, platform: "x86");
            }
            currentSolution = currentWorkspace.CurrentSolution;
        }

        void GenerateQueries()
        {
            foreach (var project in currentSolution.Projects)
            {
                currentProject = project;
                IEnumerable<IDocument> docs = null;
                try
                {
                    docs = project.Documents;
                }
                catch (Exception e)
                {
                    Logger.PrintLine("Exception loading project: " + e + "\n" + e.StackTrace);
                }
                if (docs != null)
                {
                    foreach (var doc in docs)
                    {
                        CurrentDocument = doc;
                        Logger.PrintLine(new QueryableCollector(doc).PrettyPrintAllMethodQueryResults());
                    }
                }
            }
        }
    }
}
